<template>
  <div class="search-container">
    <!-- form表单作用 手机端 用户点击搜索框时 输入法键盘会出现搜索确认按键 -->
    <form action="/">
      <van-search
        v-model="value"
        shape="round"
        show-action
        background="#0094ff"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @clear="isShowResult = false"
        @focus="isShowResult = false"
      >
        <van-icon name="arrow-left" slot="left" @click="$router.push('/')" />
      </van-search>
    </form>
    <!-- 搜索结果 -->
    <SearchResult v-if="isShowResult" :searchKey="value" />
    <!-- 搜索建议 -->
    <SearchSuggestion
      v-else-if="value"
      :keyword="value"
      @setKeyWord="setKeyWord"
    />
    <!-- 搜索历史 -->
    <SearchHistory :historyList="historyList" v-else @onSearch="onSearch" />
  </div>
</template>

<script>
// 引入组件
import SearchHistory from './compoents/search-history.vue'
import SearchResult from './compoents/search-result.vue'
import SearchSuggestion from './compoents/search-suggestion.vue'
import { getItem, setItem } from '@/utils/storage'

export default {
  name: 'search',

  components: {
    SearchHistory,
    SearchResult,
    SearchSuggestion
  },
  data () {
    return {
      value: '',
      // 控制组件显示
      isShowResult: false,
      // 从本地取出搜索历史数组，可能为null
      // 如果读取为null，则设置为空数组
      historyList: getItem(this.$conf.SEARCH_HISTORY) || []
    }
  },

  mounted () {},

  methods: {
    // 子组件选中关键字
    setKeyWord (newword) {
      // 将被选中的关键字设置给搜索框
      this.value = newword
      // 显示结果组件，隐藏建议组件
      this.isShowResult = true
    },
    // 搜索框回车触发事件
    onSearch (keyword) {
      this.value = keyword
      // 如果关键字相同 则删除原来的关键字，添加新的关键字
      const delIndex = this.historyList.findIndex((x) => x === keyword)
      // console.log(delIndex)
      if (delIndex > -1) {
        this.historyList.splice(delIndex, 1)
      }
      // 将关键字添加到数组中
      this.historyList.unshift(keyword)
      this.isShowResult = true
    },
    // 搜索框取消触发事件
    onCancel () {
      this.isShowResult = false
    }
  },

  created () {
    this.historyList = getItem(this.$conf.SEARCH_HISTORY)
    if (!this.historyList) this.historyList = []
  },

  watch: {
    // 侦听历史数据列表，并实时添加到本地
    historyList (newHistory) {
      setItem(this.$conf.SEARCH_HISTORY, newHistory)
    }
  }

  // activated () {
  //   console.log('activated->layout')
  // },
  // deactivated () {
  //   console.log('deactivated->layout')
  // }
}
</script>

<style lang="less" scoped>
.search-container {
  .van-search__action {
    background-color: #0094ff;
    color: #fff;
  }
  .van-icon-arrow-left {
    color: #fff;
    font-size: 30px;
    margin-right: 5px;
  }
}
</style>
